﻿using System;
using System.Data;
using System.Text;
using System.Web;

namespace MS.InformationManagement.Support
{
    public class CsvExportHelper
    {
        /// <summary>
        /// Exports to CSV.
        /// </summary>
        /// <param name="data">The datatable containing the data to be exported.</param>
        /// <param name="headers">The csv headers, they should appear in the same order the datatable has the data columns.</param>
        /// <param name="separator">The separator to be used in the csv file.</param>
        public static string ExportToCSV(DataTable data, string[] headers, char separator)
        {
            StringBuilder fileContent = new StringBuilder();
            
            foreach (string currentHeader in headers) {
                fileContent.Append(currentHeader);
                fileContent.Append(separator);
            }
            fileContent.Remove(fileContent.Length - 1, 1);
            fileContent.Append("\n");

            IDataReader reader = data.CreateDataReader();
            int cellCount = 0;
            
            while (reader.Read()) {
                cellCount = reader.FieldCount;
                for (int currentCell = 0; currentCell < cellCount; currentCell++) {
                    fileContent.Append(reader.GetValue(currentCell));
                    fileContent.Append(separator);
                }
                fileContent.Remove(fileContent.Length - 1, 1);
                fileContent.Append("\n");
            }

            return fileContent.ToString();
        }
    }
}
